/*
                        *********************
*************************** C SOURCE FILE ************************************
**                      *********************                               **
**                                                                          **
*/

#define _SERVER_C_SRC

/****************************************************************************/
/**                                                                        **/
/** MODULES USED                                                           **/
/**                                                                        **/
/****************************************************************************/

#include "server.h"

/****************************************************************************/
/**                                                                        **/
/** DEFINITIONS AND MACROS                                                 **/
/**                                                                        **/
/****************************************************************************/


/****************************************************************************/
/**                                                                        **/
/** TYPEDEFS AND STRUCTURES                                                **/
/**                                                                        **/
/****************************************************************************/


/****************************************************************************/
/**                                                                        **/
/** PROTOTYPES OF LOCAL FUNCTIONS                                          **/
/**                                                                        **/
/****************************************************************************/

void signal_handler_IO (int status);    //definition of signal handler
void *A(void *thread_argv);
void *B(void *thread_argv);


/****************************************************************************/
/**                                                                        **/
/** EXPORTED VARIABLES                                                     **/
/**                                                                        **/
/****************************************************************************/


/****************************************************************************/
/**                                                                        **/
/** GLOBAL VARIABLES                                                       **/
/**                                                                        **/
/****************************************************************************/

/*  serial parameter */
	char Param_strings[7][80];
	char message[90];
	int fd, tty;
	char In1;
	struct termios oldtio, newtio;       //place for old and new port settings for serial port
	struct termios oldkey, newkey;       //place tor old and new port settings for keyboard teletype
	struct sigaction saio;               //definition of signal action


/* Ethernet parameter */
	int16s 	server_sockfd, client_sockfd;
	int16s 	server_len, client_len;
	struct 	sockaddr_in server_address;
	struct 	sockaddr_in client_address;

/* program parameter */
	int SAVE = FALSE;
	FILE *input;
	FILE *output;
	int16u status;
	int16s result;
	time_t t;
	char Key;
	char buf[20],bufstr[60];
	FILE *list;
	pthread_mutex_t mutexVAR = PTHREAD_MUTEX_INITIALIZER;
	pthread_t threadA, threadB, threadC;

/****************************************************************************/
/**                                                                        **/
/** EXPORTED FUNCTIONS                                                     **/
/**                                                                        **/
/****************************************************************************/



/****************************************************************************/
/**                                                                        **/
/** LOCAL FUNCTIONS                                                        **/
/**                                                                        **/
/****************************************************************************/
int main(int argc, char *argv[])
{

/* clear socket and tty */

	close(fd);
	close(client_sockfd);

/* Ethernet config */
	/* Create an unnamed socket for the server. */
	server_sockfd = socket(AF_INET, SOCK_STREAM, 0);

	/* Assign a name to a socket. */
	server_address.sin_family = AF_INET;
	server_address.sin_addr.s_addr = inet_addr("192.168.1.245");
	server_address.sin_port = 14;
	server_len = sizeof(server_address);
	result = bind(server_sockfd, (struct sockaddr *)&server_address, server_len);
	if(result == -1)
	{
		perror("OOPS!!: bind function error\n");
		exit(1);
	}
	printf("bind function ok\n");
	/* Create a connection queue and wait for clients. */
	result = listen(server_sockfd, 5);
	if(result == -1)
	{
		perror("OOPS!!: listen function error\n");
		exit(1);
	}
	printf("listen function ok\n");
	/* Accept a connection. */
	client_len = sizeof(client_address);
	client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len);
	printf("Accept function ok\n");

/* serial config */

	//open the device(com port) to be non-blocking (read will return immediately)
	fd = open("/dev/ttyS1", O_RDWR | O_NOCTTY | O_NONBLOCK);

	//install the serial handler before making the device asynchronous
	saio.sa_handler = signal_handler_IO;
	sigemptyset(&saio.sa_mask);   //saio.sa_mask = 0;
	saio.sa_flags = 0;
	saio.sa_restorer = NULL;
	sigaction(SIGIO,&saio,NULL);

	// allow the process to receive SIGIO
	fcntl(fd, F_SETOWN, getpid());
	// Make the file descriptor asynchronous (the manual page says only
	// O_APPEND and O_NONBLOCK, will work with F_SETFL...)
	fcntl(fd, F_SETFL, FASYNC);

	tcgetattr(fd, &oldtio); // save current port settings 
	// set new port settings for canonical input processing 
	newtio.c_cflag = B9600 | CRTSCTS | CS8 | 0 | 0 | 0 | CLOCAL | CREAD;
	newtio.c_iflag = IGNPAR;
	newtio.c_oflag = 0;
	newtio.c_lflag = 0;       //ICANON;
	newtio.c_cc[VMIN]=1;
	newtio.c_cc[VTIME]=0;
	tcflush(fd, TCIFLUSH);
	tcsetattr(fd,TCSANOW,&newtio);


	list = fopen("ADC.txt","w");
	fclose(list);

	pthread_create(&threadA, NULL, &A, NULL);
	pthread_create(&threadB, NULL, &B, NULL);

	pthread_exit(NULL);
	return 0;
}
void signal_handler_IO (int status)
{
	
		
}
void *A(void *thread_argv)
{
	while(1)
	{
		clr(buf,20);
		status = read(fd,buf,10);
		if (status>0)
		{
			result = mode(buf);
			time(&t);
			if(result == 1)
			{
		printf("Analog is %c%c%c%c at %s",buf[3],buf[4],buf[5],buf[6],ctime(&t));
				clr(bufstr,60);
		sprintf(bufstr,"Analog is %c%c%c%c at %s",buf[3],buf[4],buf[5],buf[6],ctime(&t));
				if(SAVE==TRUE)
				{	
					list = fopen("ADC.txt","a");
					fprintf(list,"%s",bufstr);
					fclose(list);
				}
				write(client_sockfd,bufstr,60);
			}
			else if(result == 2)
			{
		printf("JOY is %c at %s",buf[3],ctime(&t));
		clr(bufstr,60);
		sprintf(bufstr,"JOY is %c at %s",buf[3],ctime(&t));
				write(client_sockfd,bufstr,60);
			}
		}
	}
}
void *B(void *thread_argv)
{
	while(1)
	{
		clr(buf,20);
		status = read(client_sockfd,buf,1);
		if (status>0)
		{
			if(buf[0]=='1'|buf[0]=='2'|buf[0]=='3'|buf[0]=='4'|buf[0]=='5'|buf[0]=='6'|buf[0]=='7'|buf[0]=='8'|buf[0]=='9')
			{
				write(fd,buf,1);
				printf("%c\r\n",buf[0]);
			}
			else if(buf[0] == 's')
			{
				SAVE = TRUE;
				printf("Save ADC\r\n");
			}
			else if(buf[0] == 'd')
			{
				SAVE = FALSE;
				printf("Stop save ADC\r\n");
			}
		}
	}
}


/****************************************************************************/
/**                                                                        **/
/** EOF                                                                    **/
/**                                                                        **/
/****************************************************************************/
 
